<template>
  <el-drawer v-model="props.processTracingVisible" title="流程追踪" :with-header="false" @close="onClose"
    size="calc(100vw - 252px)">
    <div class="processtracing">
      <div class="headerBox">
        <div class="header">
          <el-steps
            :active="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState : stetes(props.mainForm.value.nodeState) "
            finish-status="process" align-center :style="{ 'margin-top': '64px', heihgt: '200px' }">
            <el-step :title="item" :key="index" v-for="(item, index) in stepData"
              :icon="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState > index ? SuccessFilled : '' : stetes(props.mainForm.value.repAcceptState) > index ? SuccessFilled : ''">
             <!-- 人员和时间 -->
              <template #description>
                <div class="stepspan" v-for="(value,i) in  newModalProcessTracingData" :key="i">
                  <p class="span">{{index+1 == value?.nodeState ? value?.creator?.organName : '' }}</p>
                  <span>{{ index+1 == value?.nodeState ? value?.createTime : '' }}</span>
                </div>
              </template>

            </el-step>
          </el-steps>
        </div>
      </div>
      <div class="title">报修详情</div>
      <el-divider />
      <div class="content">
        <el-form :inline="true" :model="props.mainForm.value" class="demo-form-inline" ref="mainDetail">
          <el-row>
            <el-col :span="8">
              <el-form-item label="维修名称：">
                {{ props.mainForm.value.repName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报单位：">
                {{ props.mainForm.value.creator.organName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报人：">
                {{ props.mainForm.value.creator.name }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="上报人电话：">
                {{ props.mainForm.value.creator.phone }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="上报时间：">
                {{ props.mainForm.value.createTime }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="紧急情况：">
                <span v-if="urgency === '1'">非常紧急</span>
                <span v-else-if="urgency === '2'">一般紧急</span>
                <span v-else-if="urgency === '3'">一般</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="航站楼：">
                {{ props.mainForm.value.terminal }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="楼层：">
                {{ props.mainForm.value.eqptFloor }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="位置：">
                <el-icon @click="() => {
                  mapVisible = !mapVisible;
                }
                  " :style="{ marginRight: '10px' }">
                  <Position />
                </el-icon>
                <map-control @mapLoad="mapLoadEvent" v-if="mapVisible" :style="{ width: '90%' }"></map-control>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="设备类型：">
                {{ props.mainForm.value.eqptTypeName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="问题类型：">
                {{ props.mainForm.value.problemName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="问题描述：">
                <el-input type="textarea" placeholder="请输入内容" disabled v-model="props.mainForm.value.problemDesc">
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" v-if="props.mainForm.value.nodeState == '06'">
              <el-form-item label="挂起原因：">
                {{ props.mainForm.value.nodeContent.suspend }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="图片：">
                <el-image style="width: 100px; height: 100px;margin-left:20px" v-for="item in props.mainForm.value.files"
                  :src="useImgurl(item.resourceAddress)"></el-image>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="备注：">
                {{ props.mainForm.value.remarks }}
              </el-form-item>
            </el-col>
            <el-col :span="8"></el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </el-form>
      </div>
      <div class="title1"
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 2 : props.mainForm.value.nodeState >= 2">
        指派详情
        <el-button type="primary" :style="{ marginLeft: '10px' }"
          @click="handleShowModalProcessTracing">查看指派记录</el-button>
      </div>
      <el-divider
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 2 : props.mainForm.value.nodeState >= 2" />
      <div class="content1"
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 2 : props.mainForm.value.nodeState >= 2">
        <el-form :inline="true" :model="props.mainForm.value" class="demo-form-inline" ref="mainDetail">
          <el-row>
            <el-col :span="8">
              <el-form-item label="最后一位指派人：">
                {{ assignObj?.creator?.name }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="所属科室：">
                {{ assignObj?.creator?.organName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最后一次指派时间：">
                {{ assignObj?.createTime }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="所选维修员：">
                {{ assignObj?.nodeContent?.servicemanName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计划完成时间：">
                {{ times(assignObj?.nodeContent?.planCompleteTime) }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="故障分析：">
                <!-- <el-image style="width: 100px; height: 100px" v-for="item in assignObj?.nodeContent?.faultAnalysisList"
                  :src="item.resourceAddress"></el-image> -->
                <span v-for="item in assignObj?.nodeContent?.faultAnalysisList" style="margin-right:10px"> {{
                  item.enclosureName }}.{{ item.enclosureSuffix }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="维修方案：">
                <!-- <el-image style="width: 100px; height: 100px" v-for="item in assignObj?.nodeContent?.maintenancePlanList"
                  :src="item.resourceAddress"></el-image> -->
                <span v-for="item in assignObj?.nodeContent?.maintenancePlanList" style="margin-right:10px"> {{
                  item.enclosureName }}.{{ item.enclosureSuffix }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="工作标准">
                <el-image style="width: 100px; height: 100px" v-for="item in assignObj?.nodeContent?.workstandardsList"
                  :src="item.resourceAddress"></el-image>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="title2"
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 4 : props.mainForm.value.nodeState >= 4">
        维修详情
      </div>
      <el-divider
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 4 : props.mainForm.value.nodeState >= 4" />
      <div class="content2"
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 4 : props.mainForm.value.nodeState >= 4"
        v-for="(item, i) in serviceObj" :key="i">
        <el-form :inline="true" :model="props.mainForm.value" class="demo-form-inline" ref="mainDetail">
          <el-row>
            <el-col :span="8">
              <el-form-item label="维修开始时间：">
                {{ item.createTime }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="维修员：">
                {{ item.creator.name }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="协同人：">
                {{ item.nodeContent.servicemanName }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="维修完成时间：">
                {{ item.createTime }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="维修照片：">
                <el-image style="width: 100px; height: 100px" v-for="value in item.nodeContent.servicePhoto"
                  :src="useImgurl(value.resourceAddress)"></el-image>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="维修方式：">
                {{ item.nodeContent.serviceWay }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="维修结果：">
                {{ item.nodeContent.serviceResult }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="title3"
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 5 : props.mainForm.value.nodeState >= 5">
        维修检查结果
      </div>
      <el-divider
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 5 : props.mainForm.value.nodeState >= 5" />
      <div class="content4"
        v-if="props.mainForm.value.nodeContent?.repAcceptState ? props.mainForm.value.nodeContent.repAcceptState >= 5 : props.mainForm.value.nodeState >= 5">
        <el-form :inline="true" :model="props.mainForm.value" class="demo-form-inline" ref="mainDetail">
          <el-row>
            <el-col :span="8">
              <el-form-item label="检查时间：">
                {{ checkObj.createTime }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检查人：">
                {{ checkObj.creator?.name }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检查结果：">
                {{ checkObj.nodeContent?.serviceResult }}
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="checkObj.nodeContent">
            <el-col :span="8">
              <el-form-item label="整体评价：">
                <el-rate disabled v-model="checkObj.nodeContent.rate" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="响应效率：">
                <el-rate disabled v-model="checkObj.nodeContent.efficiency" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="维修结果：">
                <el-rate disabled v-model="checkObj.nodeContent.result" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="checkObj.nodeContent">
            <el-col :span="8">
              <el-form-item label="服务评价">
                {{ checkObj.nodeContent.rateStr }}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="现场拍照：">
                <el-image style="width: 100px; height: 100px" v-for="item in checkObj.nodeContent.photo"
                  :src="useImgurl(item.resourceAddress)"></el-image>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-divider />
      <slot name="footer">
        <div class="footer">
          <el-button type="info" plain @click="onClose">取消</el-button>
          <el-button type="warning" plain @click="Pass" v-if="!props.isProcessTracing &&
            parseInt(props.mainForm.value.repAcceptState) == 4
            ">通过</el-button>
          <el-button type="danger" plain @click="handleReject" v-if="!props.isProcessTracing &&
            parseInt(props.mainForm.value.repAcceptState) < 5
            ">驳回</el-button>
          <el-button type="warning" plain @click="handleSuspend" v-if="!props.isProcessTracing &&
            parseInt(props.mainForm.value.repAcceptState) < 5 && parseInt(props.mainForm.value.repAcceptState) != 4
            ">挂起</el-button>
          <el-button type="primary" @click="handleAssign" v-if="!props.isProcessTracing &&
            !(parseInt(props.mainForm.value.repAcceptState) > 1)
            ">指派</el-button>
        </div>
      </slot>

      <el-dialog v-model="dialogVisible" :title="dialogTitle?.[dialogTitleCategory]" width="30%" :show-close="false"
        class="elDialog" :destroy-on-close="true" @close="handleClose">
        <el-form :model="dialogForm" ref="dialogDetail">
          <div v-if="dialogTitleCategory == 'reject'">
            <el-form-item label="驳回意见:" prop="reject.nodeContent.reject" :rules="[
              { required: true, message: '驳回意见必填', trigger: 'change' },
              { max: 500, message: '不超过500字', trigger: 'change' },
            ]">
              <el-input type="textarea" v-model="dialogForm.reject.nodeContent.reject"></el-input>
            </el-form-item>
          </div>

          <div v-if="dialogTitleCategory == 'suspend'">
            <el-form-item label="挂起原因:" prop="suspend.nodeContent.suspend" :rules="[
              { required: true, message: '挂起原因必填', trigger: 'change' },
              { max: 500, message: '不超过500字', trigger: 'change' },
            ]">
              <el-input type="textarea" v-model="dialogForm.suspend.nodeContent.suspend"></el-input>
            </el-form-item>
          </div>
          <div v-if="dialogTitleCategory == 'assign'">
            <el-form-item label="维修人员:" prop="assign.nodeContent.serviceman" :rules="[
              { required: true, message: '维修人员必填', trigger: 'change' },
            ]">
              <el-select v-model="dialogForm.assign.nodeContent.serviceman" :style="{ width: '100%', marginLeft: '2px' }">
                <el-option v-for="item in memberPeopelData" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="计划完成时间:" prop="assign.nodeContent.planCompleteTime" :rules="[
              {
                required: true,
                trigger: 'change',
                validator: getValodatorplanCompleteTime,
              },
            ]">
              <el-date-picker v-model="dialogForm.assign.nodeContent.planCompleteTime" type="datetime"
                placeholder="选择日期时间" :style="{ width: '100%', marginLeft: '2px' }">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="维修员需在:" prop="assign.nodeContent.planAcceptTime" :rules="[
              {
                required: true,
                trigger: 'change',
                validator: getValodatorplanAcceptTime,
              },
            ]">
              <el-date-picker v-model="dialogForm.assign.nodeContent.planAcceptTime" type="datetime" placeholder="选择日期时间"
                :style="{ width: '80%', marginLeft: '2px' }">
              </el-date-picker>
              之前接受任务
            </el-form-item>
            <el-form-item label="逾期" prop="assign.nodeContent.overdue2" :rules="[
              {
                required: true,
                trigger: 'change',
                validator: getnodeContente,
              },
            ]">
              <el-input :style="{ width: '20%', marginLeft: '2px' }"
                v-model="dialogForm.assign.nodeContent.overdue2.unit"></el-input>
              <el-select v-model="dialogForm.assign.nodeContent.overdue2.time"
                :style="{ width: '20%', marginLeft: '2px' }">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              未接受，为
              <el-select v-model="dialogForm.assign.nodeContent.overdue2.degree"
                :style="{ width: '40%', marginLeft: '2px' }">
                <el-option v-for="item in degreeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="逾期" prop="assign.nodeContent.overdue1" :rules="[
              {
                required: true,
                validator: getnodeContenteoverdue1,
                trigger: 'change',
              },
            ]">
              <el-input :style="{ width: '20%', marginLeft: '2px' }"
                v-model="dialogForm.assign.nodeContent.overdue1.unit"></el-input>
              <el-select v-model="dialogForm.assign.nodeContent.overdue1.time"
                :style="{ width: '20%', marginLeft: '2px' }">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              未接受，为
              <el-select v-model="dialogForm.assign.nodeContent.overdue1.degree"
                :style="{ width: '40%', marginLeft: '2px' }">
                <el-option v-for="item in degreeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="紧急程度:">
              <span :style="{ paddingLeft: '20px' }">{{ urgency }}</span>
            </el-form-item>
            <el-form-item label="故障分析:">
              <div style="display:flex;">
                <el-upload v-model:file-list="dialogForm._faultAnalysisList" class="upload-demo" action="#" multiple
                  name="file" :before-upload="beforeUpload" :http-request="(option: any) => uploadAction(option, '1')">
                  <el-button :style="{ marginRight: '20px' }">选择文件</el-button>
                </el-upload>
                <span v-if="dialogForm.assign.nodeContent.faultAnalysisList.length == 0
                  ">未选择任何文件</span>
                <a href="#blank" :style="{ display: 'block', marginLeft: '20px' }">从知识库中选择</a>
              </div>
            </el-form-item>

            <el-form-item label="维修方案:">
              <div style="display:flex;">
                <el-upload v-model:file-list="dialogForm._maintenancePlanList" class="upload-demo" action="#" multiple
                  name="file" :before-upload="beforeUpload" :http-request="(option: any) => uploadAction(option, '2')">
                  <el-button :style="{ marginRight: '20px' }">选择文件</el-button>
                </el-upload>
                <span v-if="dialogForm.assign.nodeContent.maintenancePlanList.length == 0">未选择任何文件</span>
                <a href="#blank" :style="{ display: 'block', marginLeft: '20px' }">从知识库中选择</a>
              </div>
            </el-form-item>
            <el-form-item label="工作标准:">
              <div style="display:flex;">
                <el-upload v-model:file-list="dialogForm._workstandardsList" class="upload-demo" action="#" multiple
                  name="file" :before-upload="beforeUpload" :http-request="(option: any) => uploadAction(option, '3')">
                  <el-button :style="{ marginRight: '20px' }">选择文件</el-button>
                </el-upload>
                <span v-if="dialogForm.assign.nodeContent.workstandardsList.length == 0">未选择任何文件</span>
                <a href="#blank" :style="{ display: 'block', marginLeft: '20px' }">从知识库中选择</a>
              </div>
            </el-form-item>
          </div>
          <div v-if="dialogTitleCategory == 'pass'">
            <div style="margin-left: 100px;">
              <el-form-item label="整体评价：">
                <el-rate v-model="passlist.rate" />
              </el-form-item>

              <el-form-item label="响应效率：">
                <el-rate v-model="passlist.efficiency" />
              </el-form-item>

              <el-form-item label="维修结果：">
                <el-rate v-model="passlist.result" />
              </el-form-item>

              <el-form-item label="检查结果：" style="width: 300px;">
                <el-input v-model="passlist.checkResult"></el-input>
              </el-form-item>
              <el-form-item label="服务评价：" style="width: 300px;">
                <el-input v-model="passlist.rateStr"></el-input>
              </el-form-item>
              <el-form-item label="现场图片：">
                <el-upload :action="baseGeneralPath + '/fast/uploadFile'" v-model:file-list="filelists"
                  list-type="picture-card" class=" hide" :on-preview="handlePictureCardPreview"
                  :on-success="handlerUploadSuccess" :on-exceed="handleExceed" limit="10"
                  :before-upload="handlerBeforeUpload">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-upload>
                <el-dialog align-center width="auto" center v-model="dialogVisibles" action="/fast/uploadFile">
                  <div>
                    <img w-full :src="dialogImageUrl" class="dialogImageUrlimg" alt="Preview Image" />
                  </div>
                </el-dialog>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="handleClose">取消</el-button>
            <el-button type="primary" @click="handleSubmit(dialogDetail)">{{
              submitBtnText
            }}</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-drawer>
</template>

<script lang="ts" setup>
import { computed, reactive, ref } from "vue";
import mapControl from "@/components/map/index.vue";
import { store as mapStore } from "@/components/map/mapStore";
import { image } from "@/assets/index";
import {
  repairReject,
  repairSuspend,
  repairAssign,
  repairfinish
} from "@/api/maintenance/repairacceptancemanagement/services";
import { SuccessFilled, Picture, Upload } from "@element-plus/icons-vue";
import { options, degreeOptions } from "./config/utils";
import { ElMessage, FormInstance, UploadProps, UploadRawFile, dayjs } from "element-plus";
import { useStore } from "vuex";
import { uploadFiles } from "@/api/common";
import { memberPeopelData } from "./config/options";
import moment from "moment";
import _ from "lodash";
import { baseUrlConfig } from "@/config/config";
import { deleteFile } from '@/api/common'
interface ElDrawerProps {
  processTracingVisible?: boolean;
  mainForm?: any;
  isProcessTracing?: boolean;
  modalProcessTracingData?: any;
}
const baseGeneralPath = baseUrlConfig.businessBaseUrl
const stepData = [
  "01 发起报修",
  "02 指派报修",
  "03 报修接收",
  "04 维修完成",
  "05 报修检查",
  "06 报修维修完结",
];


const stetes = (item: any) => {
  if (item == '01') {
    return '02'
  }
  if (item == '02') {
    return '03'
  }
  if (item == '03') {
    return '04'
  }
  if (item == '04') {
    return '05'
  }
  if (item == '05') {
    return '06'
  }
}

const dialogDetail = ref<FormInstance>();
const filelists = ref<any[]>([])
const store = useStore();
const Users = computed(() => store.getters["user/getUserInfo"]);
// 用于保存地图坐标及相关信息
const mapPoint = ref({});
const mapLoadEvent = () => {
  const point = mapStore.BNMap.createPoint({
    x: props.mainForm.value.coordinate.longitude,
    y: props.mainForm.value.coordinate.latitude,
    spatialReference: mapStore.BNMap.spatialReference,
  });
  // 向地图添加临时图层
  const clickLayer = mapStore.BNMap.creatGraphicsLayer({ id: "clickLayer" });
  const symbolStyle = mapStore.BNSymbol.PictureMarkerSymbol(
    image.point,
    20,
    25
  );
  // 创建要素
  const picgraphic = mapStore.BNMap.graphic(point, symbolStyle);
  // 添加到地图
  clickLayer.add(picgraphic);
  mapStore.BNMap.addGraphicsLayer(clickLayer)
  mapStore.BNMap.setCenter(point);
};
// 地图点击事件--本页面暂未使用，留着备份
const mapClick = (evt: any) => {
  console.log(evt.mapPoint.x, evt.mapPoint.y);
  // 点位坐标 longitude：evt.mapPoint.x  latitude：evt.mapPoint.y
  // 区域字段在地图数据中暂时没有
  // 移除临时图层
  mapStore.BNMap.removeGraphicsLayer("clickLayer");
  // 向地图添加临时图层
  const clickLayer = mapStore.BNMap.creatGraphicsLayer({ id: "clickLayer" });
  clickLayer.removeAll();
  // 创建点
  const point = mapStore.BNMap.createPoint({
    x: evt.mapPoint.x,
    y: evt.mapPoint.y,
    spatialReference: evt.mapPoint.spatialReference,
  });
  mapStore.BNMap.setCenter(point);
  // 创建图片
  const symbolStyle = mapStore.BNSymbol.PictureMarkerSymbol(
    image.point,
    20,
    25
  );
  // 创建要素
  const picgraphic = mapStore.BNMap.graphic(point, symbolStyle);
  // 添加到地图
  clickLayer.add(picgraphic);
  mapStore.BNMap.addGraphicsLayer(clickLayer);
  // 将相关信息保存到变量
  mapPoint.value.x = evt.mapPoint.x;
  mapPoint.value.y = evt.mapPoint.y;
  // 地图区域值暂时为空
};
const mapVisible = ref(false);
let passlist = reactive({
  rate: 0,
  efficiency: 0,
  result: 0,
  checkResult: "",
  rateStr: "",
  photo: []
})
const dialogForm = reactive({
  reject: { nodeContent: { reject: "" } },
  suspend: { nodeContent: { suspend: "" } },
  assign: {
    nodeContent: {
      serviceman: "",
      planCompleteTime: "",
      planAcceptTime: "",
      overdue2: {
        time: "H",
        unit: "",
        degree: "0",
      },
      overdue1: {
        time: "D",
        unit: "",
        degree: "1",
      },
      faultAnalysisList: <any>[],
      maintenancePlanList: <any>[],
      workstandardsList: <any>[],
    },
  },
  _faultAnalysisList: <any>[],
  _maintenancePlanList: <any>[],
  _workstandardsList: <any>[],
});

const getValodatorplanAcceptTime = (rule: any, value: any, callback: any) => {
  if (!dialogForm.assign.nodeContent.planCompleteTime) {
    callback("请先填写计划完成时间");
  }
  if (!moment(value).isBefore(dialogForm.assign.nodeContent.planCompleteTime)) {
    callback("任务接收需要完成时间之前");
  } else {
    callback();
  }
};

const getValodatorplanCompleteTime = (rule: any, value: any, callback: any) => {
  if (!dialogForm.assign.nodeContent.planCompleteTime) {
    callback('计划完成时间不能为空')
  }
  if (!value) {
    dialogDetail?.value?.validateField("assign.nodeContent.planAcceptTime");
  }
  callback();
};

//格式化时间
const times = (time: any) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
}


const getnodeContente = (rule: any, value: any, callback: any) => {
  // console.log(dialogForm.assign.nodeContent.overdue1.degree,'延迟222222222');
  // console.log(dialogForm.assign.nodeContent.overdue2.degree,'延迟13333');
  let degree2 = ref(0)
  let degree1 = ref(0)

  if (dialogForm.assign.nodeContent.overdue2.time == 'H') {
    degree2.value = Number(dialogForm.assign.nodeContent.overdue2.unit)
  }
  if (dialogForm.assign.nodeContent.overdue2.time == 'D') {
    degree2.value = Number(dialogForm.assign.nodeContent.overdue2.unit) * 24
  }
  if (dialogForm.assign.nodeContent.overdue1.time == 'H') {
    degree1.value = Number(dialogForm.assign.nodeContent.overdue1.unit)
  }
  if (dialogForm.assign.nodeContent.overdue1.time == 'D') {
    degree1.value = Number(dialogForm.assign.nodeContent.overdue1.unit) * 24
  }

  if (dialogForm.assign.nodeContent.overdue1.degree == '0' && dialogForm.assign.nodeContent.overdue2.degree == '1') {
    if (degree2.value <= degree1.value) {
      callback('严重延迟时长必须长于普通延迟');
    }
  }
  if (dialogForm.assign.nodeContent.overdue1.degree == '1' && dialogForm.assign.nodeContent.overdue2.degree == '0') {
    if (degree2.value >= degree1.value) {
      callback('普通延迟时长必须少于严重延迟');
    }
  }

  if (!dialogForm.assign.nodeContent.overdue2.unit) {
    callback('逾期必填');
  }
  callback();
}
const getnodeContenteoverdue1 = (rule: any, value: any, callback: any) => {

  let degree2 = ref(0)
  let degree1 = ref(0)

  if (dialogForm.assign.nodeContent.overdue2.time == 'H') {
    degree2.value = Number(dialogForm.assign.nodeContent.overdue2.unit)
  }
  if (dialogForm.assign.nodeContent.overdue2.time == 'D') {
    degree2.value = Number(dialogForm.assign.nodeContent.overdue2.unit) * 24
  }
  if (dialogForm.assign.nodeContent.overdue1.time == 'H') {
    degree1.value = Number(dialogForm.assign.nodeContent.overdue1.unit)
  }
  if (dialogForm.assign.nodeContent.overdue1.time == 'D') {
    degree1.value = Number(dialogForm.assign.nodeContent.overdue1.unit) * 24
  }

  if (dialogForm.assign.nodeContent.overdue1.degree == '0' && dialogForm.assign.nodeContent.overdue2.degree == '1') {
    if (degree2.value <= degree1.value) {
      callback('普通延迟时长必须少于严重延迟');
    }
  }
  if (dialogForm.assign.nodeContent.overdue1.degree == '1' && dialogForm.assign.nodeContent.overdue2.degree == '0') {
    if (degree2.value >= degree1.value) {
      callback('严重延迟时长必须长于普通延迟');
    }
  }

  if (!dialogForm.assign.nodeContent.overdue1.unit) {
    callback('逾期必填');
  }
  callback();
}

const dialogVisible = ref(false);
const dialogTitleCategory: any = ref("reject");
const dialogTitle: any = {
  reject: "驳回",
  suspend: "挂起",
  assign: "责任单位接受并指派",
  pass: '通过'
};
const props = defineProps<ElDrawerProps>();
if (props) {

}
const filelist = (imgs: any) => {

}
//图片回显得函数
const useImgurl = (url: string) => {
  const imgUrls = '/general-business'
  if (url.includes('/filePath')) {
    url = url.replace('/filePath', '')
  }
  if (url.includes('/api')) {
    url = url.replace('/api', '')
  }
  if (url.includes('/general-business')) {
    url = url.replace('/general-business', '')
  }
  return imgUrls + url
}

const emit = defineEmits(["close", "getListData", "showModalProcessTracing"]);
const handleClose = () => {
  (dialogForm.reject = { nodeContent: { reject: "" } }),
    (dialogForm.suspend = { nodeContent: { suspend: "" } }),
    (dialogForm.assign = {
      nodeContent: {
        serviceman: "",
        planCompleteTime: "",
        planAcceptTime: "",
        overdue2: {
          time: "H",
          unit: "",
          degree: "0",
        },
        overdue1: {
          time: "D",
          unit: "",
          degree: "1",
        },
        faultAnalysisList: <any>[],
        maintenancePlanList: <any>[],
        workstandardsList: <any>[]
      },
    }),
    (dialogForm._faultAnalysisList = []);

  dialogForm._maintenancePlanList = [];
  dialogForm._workstandardsList = []
  dialogVisible.value = false;
};
const lastMender = computed(() => {
  return {
    id: Users.value?.userId,
    name: Users.value?.userName,
    phone: Users.value?.phone,
    organId: Users.value?.organId,
    organName: Users.value?.organName,
  };
});

const newModalProcessTracingData = computed(() => {
  const res = _.cloneDeep(props.modalProcessTracingData);
  const groupedArr = _.groupBy(res, "nodeState");
  if (groupedArr["07"]) {
    delete groupedArr["07"];
  }
  const uniqueArr = _.reduce(
    groupedArr,
    (result: any, group) => {
      const maxTime = _.maxBy(group, "createTime");
      result.push(maxTime);
      return result;
    },
    []
  );
  return uniqueArr;
});


const assignObj = computed(() => {
  const res = props.modalProcessTracingData?.filter((item: any) => {
    return item?.nodeState == "02";
  });
  return _.maxBy(res, (item: any) => new Date(item.createTime));
});

const serviceObj = computed(() => {

  const serviceObjs = ref<any[]>([])
  props.modalProcessTracingData.forEach((item: any) => {
    if (item.nodeState === '03' && item.nodeContent) {
      serviceObjs.value.push(item)
    }
  })
  if (props.mainForm.value.nodeContent) {
    serviceObjs.value.push(props.mainForm.value)
  }

  return serviceObjs.value
});
const serviceResObj = computed(() => {
  const res = props.modalProcessTracingData?.filter((item: any) => {
    return item?.nodeState == "04";
  });
  return _.maxBy(res, (item: any) => new Date(item.createTime));
});


const checkObj = computed(() => {
  const res = props.modalProcessTracingData?.filter((item: any) => {
    return item?.nodeState == "05";
  });
  const checkObjs = ref<any[]>([])
  props.modalProcessTracingData.forEach((item: any) => {
    if (item.nodeState == "05") {
      checkObjs.value.push(item)
    }
  })


  // return _.maxBy(res, (item: any) => new Date(item.createTime));
  return checkObjs.value[0] || []
});
const urgency = computed(() => {
  const cellValue = props.mainForm.value.urgency;
  let renderText = "";
  if (cellValue == "1") renderText = "非常紧急";
  if (cellValue == "2") renderText = "一般紧急";
  if (cellValue == "3") renderText = "一般";
  return renderText;
});
const rate = computed(() => {
  console.log(checkObj.value.nodeContent.rate, 'checkObj1506515');

  return checkObj.value.nodeContent.rate;
});
const efficiency = computed(() => {
  return checkObj?.value?.nodeContent?.rate;
});
const result = computed(() => {
  return checkObj?.value?.nodeContent?.rate;
});

const handleSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // try {
  formEl?.validate(async (valid) => {
    if (valid) {
      if (dialogTitleCategory.value == "reject") {
        const res = await repairReject({
          ...props.mainForm.value,
          mender: lastMender.value,
          nodeContent: dialogForm.reject.nodeContent,
        });
      }
      if (dialogTitleCategory.value == "suspend") {
        await repairSuspend({
          ...props.mainForm.value,
          mender: lastMender.value,
          nodeContent: dialogForm.suspend.nodeContent,
        });
      }
      if (dialogTitleCategory.value == "assign") {
        await repairAssign({
          ...props.mainForm.value,
          mender: lastMender.value,
          nodeContent: dialogForm.assign.nodeContent,
        });
      }
      if (dialogTitleCategory.value == 'pass') {
        const res = await repairfinish({
          ...props.mainForm.value,
          mender: lastMender.value,
          nodeContent: passlist,
        })
        if (res.code == '1') {
          passlist.checkResult = '',
            passlist.rate = 0,
            passlist.efficiency = 0,
            passlist.result = 0,
            passlist.checkResult = "",
            passlist.rateStr = "",
            passlist.photo = []
          filelists.value = []
        }
      }

      ElMessage.success("操作成功");
      return onClose();
    } else {
      console.log("error submit!");
      return false;
    }
  });
  // } catch (error: any) {
  //   ElMessage.error(error.message);
  // }
};
const onClose = () => {
  mapVisible.value = false;
  (dialogForm.reject = { nodeContent: { reject: "" } }),
    (dialogForm.suspend = { nodeContent: { suspend: "" } }),
    (dialogForm.assign = {
      nodeContent: {
        serviceman: "",
        planCompleteTime: "",
        planAcceptTime: "",
        overdue2: {
          time: "H",
          unit: "",
          degree: "0",
        },
        overdue1: {
          time: "D",
          unit: "",
          degree: "1",
        },
        faultAnalysisList: <any>[],
        maintenancePlanList: <any>[],
        workstandardsList: <any>[]
      },
    }),
    (dialogForm._faultAnalysisList = []);

  dialogForm._maintenancePlanList = [];
  dialogForm._workstandardsList = []

  dialogVisible.value = false;
  dialogTitleCategory.value = "reject";
  emit("close");
  emit("getListData");
};
const Pass = () => {
  dialogTitleCategory.value = "pass";
  dialogVisible.value = true;
}

const handleReject = () => {
  dialogTitleCategory.value = "reject";
  dialogVisible.value = true;
};
const handleSuspend = () => {
  dialogTitleCategory.value = "suspend";
  dialogVisible.value = true;
};
const handleAssign = () => {
  dialogTitleCategory.value = "assign";
  dialogVisible.value = true;
};
const beforeUpload = (file: UploadRawFile) => {
  const isAllowedExtension =
    /\.(jpg|jpeg|png|gif|xls|xlsx|doc|docx|ppt|pptx|pdf)$/i.test(file.name);
  const isAllowedSize = file.size / 1024 / 1024 < 100;
  if (!isAllowedExtension) {
    ElMessage.error("只允许上传图片、Excel、Word、PPT和PDF格式的文件");
  }
  if (!isAllowedSize) {
    ElMessage.error("文件大小不能超过100M");
  }
  return isAllowedExtension && isAllowedSize;
};
const uploadAction = (option: any, isFaultAnalysis: any) => {
  console.log(option, 'isFaultAnalysis');
  const type = isFaultAnalysis == '1' ? "faultAnalysisList" : isFaultAnalysis == '2' ? "maintenancePlanList" : "workstandardsList";
  let param = new FormData();
  param.append("file", option.file);
  param.append("fileName", option.filename);
  console.log(param, 'param');
  uploadFiles(param).then((res: any) => {
    if (res && res.code == 1) {
      dialogForm.assign.nodeContent?.[type].push({
        enclosureContent: res.data.enclosureContent,
        enclosureName: res.data.enclosureName,
        enclosureSuffix: res.data.enclosureSuffix,
        resourceAddress: res.data.resourceAddress,
        enclosureCode: res.data.enclosureCode,
      });
      console.log(dialogForm.assign.nodeContent, 'console.log(dialogForm.assign.nodeContent);');
      ElMessage.success("上传成功！");
    } else {
      if (res && res.msg) {
        ElMessage.error(res.msg);
      } else {
        ElMessage.error("上传失败！");
      }
    }
  });
};
const dialogImageUrl = ref('')
const dialogVisibles = ref(false)
const handlePictureCardPreview = (uploadFile: any) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisibles.value = true
}

const handlerUploadSuccess: UploadProps['onSuccess'] = (resp, uploadFile, uploadFiles) => {
  if (resp.code === '1') {
    const item = {
      enclosureContent: resp.data.enclosureCode,
      enclosureName: resp.data.enclosureName,
      enclosureSuffix: resp.data.enclosureSuffix,
      resourceAddress: resp.data.resourceAddress,
      enclosureCode: resp.data.enclosureCode
    }
    passlist.photo.push(item)
    // console.log(passlist.photo,'item');

  }
}

const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.error('上传文件数不能超过10个')
}

const handlerBeforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  // console.log(rawFile)
  const fileSuffix = rawFile.name.substring(rawFile.name.lastIndexOf('.') + 1)
  const whiteList = ['jpg', 'png', 'JPG', 'PNG']
  if (whiteList.indexOf(fileSuffix) === -1) {
    ElMessage.error('上传文件类型只能是 jpg,png格式')
    return false
  }
  if (rawFile.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小只能在10M以内')
    return false
  }
}
// const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
//   // console.log(uploadFile, uploadFiles)
//   const code = uploadFile.response?.data?.enclosureCode
//   delFile(code)
//   // hideUpload.value = false
//   const values: Array<any> = []
//   passlist.photo.forEach((item, index) => {
//     if (item.enclosureCode !== code) {
//       values.push(item)
//     }
//   })
//   passlist.photo = values
// }
const delFile = (code: string) => {
  deleteFile(code).then(res => {
  })
}

const handleShowModalProcessTracing = () => {
  emit("showModalProcessTracing", props.mainForm.value);
};

const submitBtnText = computed(() => {
  if (dialogTitleCategory.value == "reject") return "驳回";
  if (dialogTitleCategory.value == "suspend") return "挂起";
  if (dialogTitleCategory.value == "pass") return "通过";
  return "确认指派";
});
</script>

<style lang="less" scoped>
.processtracing {
  height: 96%;
  display: flex;
  flex-direction: column;
  padding-top: 164px;

  .headerBox {
    position: fixed;
    width: 80%;
    height: 164px;
    top: 0;
    background-color: #fff;
    z-index: 1;
  }

  .header {
    height: 200px;

    :deep(.el-steps) {
      .el-step__head {
        border-color: #4d7fcd;
        height: 28px;
      }

      .el-step__line {
        width: 80%;
        margin-left: 10%;
        background-color: #4d7fcd;
      }

      .el-icon svg {
        color: #4d7fcd;
      }

      .el-step__head.is-wait .el-step__icon .el-step__icon-inner {
        opacity: 0;
      }

      .el-step__title {
        position: absolute;
        top: -44px;
        left: 94px;
      }

      .el-step.is-center .el-step__description {
        padding-top: 10px;
      }
    }
  }

  .title {
    height: 16px;
    line-height: 16px;
    font-size: 16px;
  }

  .title:before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 14px;
    background-color: #4d7fcd;
    margin-right: 20px;
    vertical-align: middle;
  }

  .content {
    flex: 1;
    padding-bottom: 20px;
  }

  .title1 {
    height: 16px;
    line-height: 16px;
    font-size: 16px;
  }

  .title1:before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 14px;
    background-color: #4d7fcd;
    margin-right: 20px;
    vertical-align: middle;
  }

  .content1 {
    flex: 1;
    padding-bottom: 20px;
  }

  .title2 {
    height: 16px;
    line-height: 16px;
    font-size: 16px;
  }

  .title2:before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 14px;
    background-color: #4d7fcd;
    margin-right: 20px;
    vertical-align: middle;
  }

  .content2 {
    flex: 1;
    padding-bottom: 20px;
  }

  .title3 {
    height: 16px;
    line-height: 16px;
    font-size: 16px;
  }

  .title3:before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 14px;
    background-color: #4d7fcd;
    margin-right: 20px;
    vertical-align: middle;
  }

  .content3 {
    flex: 1;
    padding-bottom: 20px;
  }

  .footer {
    position: fixed;
    bottom: 0;
    padding-bottom: 10px;
    width: 84%;
    height: 40px;
    line-height: 45px;
    background: #fff;
    text-align: center;
    z-index: 1;
    border-top: 1px solid #dcdfe6;
  }
}

.stepspan {
  width: 100%;
  height: 100%;
  margin-left: 50px;

  .span {
    margin-right: 90px
  }
}

:deep(.el-upload-list__item) {
  width: 300px;

}


.dialog-footer {
  position: absolute;
  bottom: 40px;
  left: 270px;
}</style>
